package com.singzi.leetcode.N400;

import java.util.Arrays;
import java.util.Comparator;
import java.util.TreeSet;

public class T0347 {
    public static void main(String[] args) {
        int i = 4;
        int []nums = {1,1,1,2,2,3,2,2,2,2,2,2,2,5,5,5,5,5,5,5,5,5};
        Solution0347 solution0347 = new Solution0347();
        solution0347.topKFrequent(nums, i);
    }
}
class Solution0347 {
    public int[] topKFrequent(int[] nums, int k) {
        Arrays.sort(nums);
        TreeSet<int[]> set = new TreeSet<>(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if(o1[0] != o2[0]) return o1[0]- o2[0];
                else return o1[1] - o2[1];
            }
        });
        int cont = 1;
        for(int i = 1;i < nums.length;i++){
            if(nums[i] != nums[i-1]){
                set.add(new int[]{cont, nums[i-1]});
                cont = 1;
            }else {
                cont++;
            }
        }
        if(cont > 1) set.add(new int[]{cont, nums[nums.length-1]});
        int []ans = new int[k];
        for (int i = 0; i < k; i++) {
            ans[i] = set.last()[1];
            set.remove(set.last());
        }
        return ans;


    }
}
